//
//  HMNetworkTools.swift
//  3.Swift网络请求的封装
//
//  Created by teacher on 16/11/13.
//  Copyright © 2016年 itcast. All rights reserved.
//



import UIKit
//cocoapods管理的第三方框架在使用的时候只需要导入模块就行,不需要使用到桥接文件
import AFNetworking


//声明枚举
enum HTTPMethod: Int {
    case GET = 0
    case POST
}

class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let shared: HMNetworkTools = {
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //声明封装的函数 
    /*
     1.请求方法
     2.urlString
     3.参数
     4.请求的回调
        - 成功
        - 失败
     */
    func request(method: HTTPMethod,urlString: String, parameters: Any?,finished: @escaping (Any?,Error?) -> ()) {
        
        let successCallBack = { (task: URLSessionDataTask,responseObject: Any?) -> () in
            //这里需要使用到参数
            finished(responseObject, nil)
        }
        
        //失败的回调
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> () in
            //输出错误信息
            print(error)
            finished(nil, error)
        }
        
        if method == .GET {
            self.get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        } else {
            self.post(urlString, parameters: parameters, progress: nil, success:successCallBack, failure: failureCallBack)
        }
    }
}
